"use client";
import React, { useEffect, useState } from "react";
import {
  Button,
  Modal,
  Popconfirm,
  Tabs,
  theme,
  Flex,
} from "antd";
import {
  UserAddOutlined,
  TeamOutlined,
  RedoOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { Space, Table, Tag } from "antd";
import type { TableProps } from "antd";
import {
  DatePicker,
  Form,
  Input,
  Select,
} from "antd";
import Fometype from "./fometype";
import axios from "axios";
import dayjs from "dayjs";
interface DataType {
  time: any;
  Customer: any;
  price: any;
  bjnum: any;
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}
type TableRowSelection<T extends object = object> =
  TableProps<T>["rowSelection"];

export default function lxy(props) {
    const {
      token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
      console.log("selectedRowKeys changed: ", newSelectedRowKeys);
      setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection: TableRowSelection<DataType> = {
      selectedRowKeys,
      onChange: onSelectChange,
      selections: [
        Table.SELECTION_ALL,
        Table.SELECTION_INVERT,
        Table.SELECTION_NONE,
        {
          id: "odd",
          text: "",
          onSelect: (changeableRowKeys) => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
              if (index % 2 !== 0) {
                return false;
              }
              return true;
            });
            setSelectedRowKeys(newSelectedRowKeys);
          },
        },
        {
          key: "even",
          text: "",
          onSelect: (changeableRowKeys) => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changeableRowKeys.filter((_, index) => {
              if (index % 2 !== 0) {
                return true;
              }
              return false;
            });
            setSelectedRowKeys(newSelectedRowKeys);
          },
        },
      ],
    };
  
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "关联订单",
      dataIndex: "name",
    },
    {
      title: "订单归属人",
      dataIndex: "stage",
    },
    {
      title: "回款期次",
      dataIndex: "bjnum",  sorter: {
        compare: (a, b) => a.bjnum - b.bjnum,
        multiple: 2,
      },
      showSorterTooltip: false,
    },
    {
      title: "计划回款金额",
      dataIndex: "price",
      sorter: {
        compare: (a, b) => a.price - b.price,
        multiple: 2,
      },
      render: (record) => (
       <div>
        ￥{record}
       </div>
      ),
      showSorterTooltip: false,
    },
    {
      title: "已回款金额",
      dataIndex: "Customer",  sorter: {
        compare: (a, b) => a.Customer - b.Customer,
        multiple: 2,
      },
      showSorterTooltip: false,
    },
    {
      title: "计划回款日期",
      dataIndex: "time",  sorter: {
        compare: (a, b) => a.time - b.time,
        multiple: 2,
      },
        render: (data) => {
              return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
            },
      showSorterTooltip: false,
    },
    {
      title: "回款状态",
      dataIndex: "days",
      render: (days) => {
        return (
          <Flex>
            <Tag color={days ? "blue" : "red"}>
              {days ? "已完成" : "未完成"}
            </Tag>
          </Flex>
        );
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              showModal();
              setTitle("编辑");
              setObjItem(record);
            }}
          >
            编辑
          </a>
          <Popconfirm
            title="删除提示"
            description="是否确定删除?"
            onConfirm={async () => {
              await axios.delete(`http://localhost:3000/posts/${record.id}`, {
                headers: { "Content-Type": "application/json" },
              });
              getDate();
            }}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const [posts, setDate] = useState([]);
  // 获取所有数据
  const getDate = async () => {
    let res = await axios
      .get("http://localhost:3000/posts")
      .then((res) => res.data);
    setDate(res);
  };
  useEffect(() => {
    getDate();
  }, []);
  console.log(posts);

  const [isModalOpen, setIsModalOpen] = useState(false);

  const [title, setTitle] = useState("添加");
  const [objItem, setObjItem] = useState({});

  const showModal = () => {
    setIsModalOpen(true);
  };

  // 编辑数据
  const handleOk = async (obj: any) => {
    setIsModalOpen(false);
    await axios.patch(`http://localhost:3000/posts/${obj.id}`, obj, {
      headers: { "Content-Type": "application/json" },
    });
    getDate();
  };

  // 添加数据
  const handleCancel = async (obj: any) => {
    setIsModalOpen(false);
    await axios.post("http://localhost:3000/posts", obj, {
      headers: { "Content-Type": "application/json" },
    });
    getDate();
  };
  const [keyword, setKeyword] = useState("");
  const [customerStatus, setCustomerStatus] = useState("");
  const [customerType, setCustomerType] = useState("");
  // 搜索事件
  const handleSearch = async () => {
    try {
      const response = await axios.get("http://localhost:3000/posts", {
        params: {
          name_like: keyword != "" ? keyword : undefined,
          days_like: customerStatus != "" ? customerStatus : undefined,
          time_like: customerType != "" ? customerType : undefined,
        },
      });
      console.log(response.data);
      setDate(response.data);
    } catch (error) {
      console.error("搜索出错:", error);
    }
  };
  let [form] = Form.useForm();
  return (
    <div>
      <>
        <div>
          <Tabs
            defaultActiveKey="1"
            items={[
              {
                label: "全部客户",
                key: "1",
                // children: '全部客户',
              },
              {
                label: "我的客户",
                key: "2",
                // children: '我的客户',
              },
              {
                label: "下属客户",
                key: "3",
                // children: '下属客户',
              },
              {
                label: "重点客户",
                key: "4",
                // children: '重点客户',
              },
              {
                label: "我协作的",
                key: "5",
                // children: '我协作的',
              },
              {
                label: "下属协作的",
                key: "6",
                // children: '下属协作的',
              },
            ]}
          />
        </div>
        <Form
          style={{
            maxWidth: 1200,
            display: "flex",
            justifyContent: "space-between",
          }}
          form={form}
        >
          <Form.Item style={{ width: "160px" }} name="name">
            <Input
              placeholder="搜索关键词"
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
            />
          </Form.Item>
          <Form.Item style={{ width: "160px" }} name="days">
            <Select
              placeholder="回款状态"
              onChange={(e) => setCustomerStatus(e)}
              options={[
                { value: true, label: "已完成" },
                { value: false, label: "未完成" },
              ]}
            ></Select>
          </Form.Item>
          <Form.Item style={{ width: "160px" }}>
            <DatePicker
              placeholder="计划回款日期"
              onChange={(e) => {
                setCustomerType(e);
              }}
            />
          </Form.Item>
          <Form.Item style={{ width: "160px" }}>
            <Input suffix={<UserAddOutlined />} placeholder="订单所属人员" />
          </Form.Item>
          <Form.Item style={{ width: "160px" }}>
            <Input suffix={<TeamOutlined />} placeholder="订单所属部门" />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={handleSearch}
            >
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              style={{ width: "100px" }}
              icon={<RedoOutlined />}
              onClick={() => {
                form.resetFields();
                getDate();
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
        <Button
          type="primary"
          onClick={() => {
            showModal();
            setTitle("添加");
            setObjItem({});
          }}
        >
          添加
        </Button>
        <Modal
          title={title}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={null}
        >
          <Fometype
            title={title}
            onCancel={handleCancel}
            onOk={handleOk}
            objItem={objItem}
            key={new Date().getTime()}
          ></Fometype>
        </Modal>
        <Table<DataType> showSorterTooltip={{ target: "sorter-icon" }} rowSelection={rowSelection} columns={columns} dataSource={posts} rowKey='id'/>
      </>
    </div>
  );
}
